
/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup  分类
 * @api {POST} api/category/list 分类列表
 * @apiName api/category/list
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/category/list', {
 *     storeID: '店铺ID',
 *     kind: '分类级别',
 *     parentID: '父级分类ID'
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {number} storeID 店铺ID
 * @apiParam {number} [kind] 1: 一级分类， 2: 二级分类 不传获取所有分类
 * @apiParam {number} [parentID] Kind 为 1 时无意义，Kind 为 2 时是父级分类的 ID
 * @apiSuccess (请求成功) {Array} categorylist 分类列表
 * @apiuse  ErrorResponse
 */

const { query } = require('../../helper/db');
const { door, ok } = require('../../helper/util');

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var user = await door(token);
  var params = ctx.request.body;
  var sql = ['select * from category where 1 = 1'];
  var values = [];
  
  var { storeID, kind, parentID } = params;
  
  sql.push('and storeid = ?');
  values.push(storeID);

  if (kind) {
    sql.push('and kind = ?');
    values.push(kind);
    if (kind === 2) {
      sql.push('and parentid = ?');
      values.push(parentID);
    }
  }
  var categorylist = await query(sql.join(' '), values);
  ctx.body = ok(categorylist);
}